import Ajax from "./ajax.js";
import {
    ERROR_HTTP_CODE,
    ERROR_HTTP_CODE_TEXT,
    ERROR_REQUEST,
    ERROR_REQUEST_TEXT,
    ERROR_TIMEOUT,
    ERROR_TIMEOUT_TEXT,
    ERROR_ABORT,
    ERROR_ABORT_TEXT,
} from './constants.js'

const ajax = (url,options)=>{
    // 实例化
    // return new Ajax(url,options).getXHR();
    let xhr;
    // 实例化 promise
    const promise = new Promise((resolve,reject)=>{
        xhr = new Ajax(url,{
            ...options,
            ...{
                success(response){resolve(response);},
                httpCodeError(status){
                    reject({
                        type:ERROR_HTTP_CODE,
                        etxt:ERROR_HTTP_CODE_TEXT + status
                    });
                },
                error(){
                    reject({
                        type:ERROR_REQUEST,
                        text:ERROR_REQUEST_TEXT
                    });
                },
                abort(){
                    reject({
                        type:ERROR_ABORT,
                        text:ERROR_ABORT_TEXT
                    });
                },
                timeout(){
                    reject({
                        type:ERROR_TIMEOUT,
                        text:ERROR_TIMEOUT_TEXT
                    })
                }
            }
        }).getXHR();
    });

    promise.xhr = xhr;
    promise.ERROR_ABORT = ERROR_ABORT;
    promise.ERROR_HTTP_CODE = ERROR_HTTP_CODE;
    promise.ERROR_REQUEST = ERROR_REQUEST;
    promise.ERROR_TIMEOUT = ERROR_TIMEOUT;

    return promise;
}

// get 请求
const get = (url,options)=>{
    return ajax(url,{...options,method:'GET'});
}

// 获取 JSON 格式的数据
const getjson = (url,options)=>{
    return ajax(url,{...options,method:'GET',responseType:'json'});
}

// post 请求
const post = (url,options)=>{
    return new Ajax(url,{...options,method:'POST'});
}

export {ajax,get,getjson,post};

